package ua.amsoft.brelok.task;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;

import ua.amsoft.brelok.constant.Constants;
import ua.amsoft.brelok.manager.HttpManager;
import android.os.AsyncTask;
import android.util.Log;

/**
 * {@link AsyncTask} extenstion for device authentication
 * 
 * @author Tair Mustafaiev
 */
public class AuthenticationTask extends AsyncTask<String, Void, Boolean> {
    
    private static final String TAG = AuthenticationTask.class.getName();
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    @Override
    protected final Boolean doInBackground(final String... params) {
        try {
            return checkAuthentication(params[0], params[1]);
        } catch (final Exception e) {
            Log.e(AuthenticationTask.TAG, e.getLocalizedMessage());
        }
        return false;
    }
    
    /**
     * Checks device authentication
     * 
     * @param url - Server's url
     * @param imei - phone's IMEI number
     * @return <code>boolean true</code> or <code>false</code> is device
     *         authenticated
     */
    private boolean checkAuthentication(final String url, final String imei) {
        final HttpManager httpManager = new HttpManager();
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(Constants.PREF_IMEI_KEY, imei));
        final HttpResponse response = httpManager.doPost(url, params);
        if (response != null) {
            final StatusLine statusLine = response.getStatusLine();
            if (HttpStatus.SC_OK == statusLine.getStatusCode()) {
                return true;
            }
        }
        // TODO change to FALSE!!!!!
        return true;
    }
    
}
